package com.coffee.mybatis;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;

import java.util.Set;

/**
 * @author songkui
 * @since 2024/6/8 10:15
 */
public class CoffeeDynamicTableNameHandler implements TableNameHandler {

    private final Set<String> tableNameSet;

    public CoffeeDynamicTableNameHandler(DynamicTableNameConfigProperties dynamicTableNameConfigProperties){
        tableNameSet = dynamicTableNameConfigProperties.getPrefix();
    }
    @Override
    public String dynamicTableName(String sql, String tableName) {

        if (tableNameSet.contains(tableName)){
            try {
                String tn = CoffeeDynamicTableNameContextHolder.getTableName();
                if (StrUtil.isEmpty(tn)){
                    return tableName;
                }else {
                    return tableName+tn;
                }
            }finally {
                CoffeeDynamicTableNameContextHolder.clear();
            }
        }
        return tableName;
    }

}
